var tld = require('tldjs');
var url = require("url");
var domain = require("domain");
module.exports = function(req, res, next) {
	var referer = req.header("referer") || "";
	http_header = referer.indexOf("https://") === 0 ? "https://" : "http://"
	var host = referer.replace(http_header, "").split("/")[0];
	if (host) {
		var origin = http_header + host;
	} else {
		origin = req.header("origin");
		host.replace(http_header, "");
	}
	var domain = tld.getDomain(origin) || "";
	req.headers["origin"] = origin;
	req.headers["host"] = host;
	req.headers["domain"] = domain;
	req.headers["protocol"] = http_header.replace("//", "");
	var user_ip_list = req.headers["user_ip_list"] = req.headers["x-forwarded-for"] || req.headers["x-remote-ip"] || req.ip;
	req.headers["user_ip"] = user_ip_list.split(",")[0];
	origin || (origin = "");
	host || (host = "");

	var origin_result = "http://www.datnor.com";
	console.log(origin);
	if (origin.indexOf("http://localhost:") === 0 || origin.indexOf("http://192.168.") === 0 || origin.indexOf("chrome-extension://") === 0) {
		//开发模式
		origin_result = origin;
	} else {
		origin_result = "";
	}

	res.header("Access-Control-Allow-Credentials", true);
	res.header("Access-Control-Allow-Origin", origin_result);
	res.header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
	res.header("Access-Control-Allow-Headers", "X-PINGOTHER, Set-Cookie, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version")
		//设定P3P规范
	res.header("P3P", "CP=CAO PSA OUR");
	console.log("访问者标志：", req.header("User-Agent"));
	next();
}